﻿using System.Collections.Generic;
using System.Data;

namespace Learun.Util
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：研发部
    /// 日 期：2020.04.13
    /// 描 述：Datatable扩展
    /// </summary>
    public static partial class DataTableExtensions
    {
        /// <summary>
        /// 将Datatable转为 List转换依据 datatable 列名 与  属性名相同
        /// </summary>
        /// <param name="tab">DataTable对象</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable tab) where T : class, new()
        {
            if (tab == null) return null;
            var result = new List<T>();
            if (tab.Rows.Count == 0) return result;

            var ttype = typeof(T);

            foreach (DataRow item in tab.Rows)
            {
                var t = new T();
                foreach (DataColumn c in tab.Columns)
                {
                    var cname = c.ColumnName;
                    try
                    {
                        ttype.GetProperty(cname).SetValue(t, item[c]);
                    }
                    catch { }
                }
                result.Add(t);
            }
            return result;
        }
    }
}
